﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Model;

namespace TestWindowsFormsApplication
{
    public class LuluHelper
    {
        static List<Country> countries = new List<Country>();
        static List<State> states = new List<State>();

        static LuluHelper()
        {
            LoadCountry();
            LoadState();
        }

        public static Country GetCountry(string code)
        {
            return countries.FirstOrDefault(w => w.Code == code);
        }
        public static Country GetCountryByNameCN(string name)
        {
            return countries.FirstOrDefault(w => w.NameCN == name);
        }
        public static State GetState(string code)
        {
            return states.FirstOrDefault(w => w.Code == code);
        }

        private static void LoadCountry()
        {
            using (StreamReader reader = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "国家代码和全称.txt"))
            {
                string text = reader.ReadToEnd();
                var lines = text.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                int id = 0;
                lines.ForEach(x =>
                {
                    var codes = x.Split(new char[] { ',', '，' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < codes.Length; i++)
                    {
                        codes[i] = codes[i].Trim();
                    }
                    if (codes.Length == 4 && int.TryParse(codes[0], out id))
                    {
                        countries.Add(new Country { ID = id, Code = codes[1], NameEN = codes[2].ToUpper(), NameCN = codes[3] });
                    }
                });
            }
        }

        private static void LoadState()
        {
            using (StreamReader reader = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "州名称缩写.txt"))
            {
                string text = reader.ReadToEnd();
                var lines = text.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                int id = 0;
                lines.ForEach(x =>
                {
                    var codes = x.Split(new char[] { ',', '，' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < codes.Length; i++)
                    {
                        codes[i] = codes[i].Trim();
                    }
                    if (codes.Length > 1)
                    {
                        states.Add(new State { Code = codes[0], Name = codes[1].ToUpper() });
                    }
                });
            }
        }
    }
}
